package sz.szsmk.citizencard.mvp.presenter;

import android.os.Looper;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.youzan.spiderman.utils.MD5Utils;

import java.util.List;

import javax.inject.Inject;

import rx.functions.Action1;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.bean.request.AccessTokenRequest;
import sz.szsmk.citizencard.model.network.bean.request.GetOrderOpenid;
import sz.szsmk.citizencard.model.network.bean.request.GetTokenReq;
import sz.szsmk.citizencard.model.network.bean.request.IBaseRequest;
import sz.szsmk.citizencard.model.network.bean.request.QueryNgFinanceReq;
import sz.szsmk.citizencard.model.network.bean.request.QueryPageResourceReq;
import sz.szsmk.citizencard.model.network.bean.request.SignInReq;
import sz.szsmk.citizencard.model.network.bean.request.UserBehaviorBrowseReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.FirstSearchUserLevelRes;
import sz.szsmk.citizencard.model.network.bean.response.GetOrderOpenidRes;
import sz.szsmk.citizencard.model.network.bean.response.GetTokenRes;
import sz.szsmk.citizencard.model.network.bean.response.HomeWhxfRes;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.model.network.bean.response.QueryNgFinanceRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryOrderCountRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryPageResourceRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.SignInRes;
import sz.szsmk.citizencard.model.network.bean.response.UserCardFavResponse;
import sz.szsmk.citizencard.mvp.contract.IMineContact;
import sz.szsmk.citizencard.mvp.contract.IRealNameContact;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.retrofitrxjava.newversion.ApiCallback;
import sz.szsmk.citizencard.retrofitrxjava.newversion.HttpDateSource;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.model.network.bean.response.CouponListBean;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.StringUtils;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/12 16:25
 * description:
 */
public class IMinePresenter extends IBasePresenter implements
        IMineContact.IMinePresenter<IMineContact.IMineView> {

    private NetworkDateSources mNetworkDateSource;
    GsdxNetApi gsdxNetApi;

    @Inject
    public IMinePresenter(GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;

        this.mNetworkDateSource = NetworkDateSources.getInstance();
    }

    @Override
    public void getUserInfo() {
        IBaseRequest userInfoReq = new IBaseRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        userInfoReq.setAccess_token(access_token);
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        userInfoReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
        String key = "access_token=" + access_token + "&device_id=" + androidId + "&key=" + refresh_token;
        String stringMd5 = MD5Utils.getStringMd5(key).toUpperCase();
        userInfoReq.setSign(stringMd5);
        String json = new Gson().toJson(userInfoReq);
        L.e(Constant.TAG, "getUserInfoZhsz:" + json);
        mNetworkDateSource.getUserInfoZhsz(userInfoReq, new SubscribeResult<IUserInfo>() {
            @Override
            protected void onOk(IUserInfo response) {
                String mobile = response.getUserEx().getMobile();
                ACache.get(DaggerApplication.getIns()).remove("mobile");
                ACache.get(DaggerApplication.getIns()).put("mobile", mobile);
                ACache.get(DaggerApplication.getIns()).put("userId", response.getUserEx().getId() + "");
                String json = new Gson().toJson(response);
                ACache.get(DaggerApplication.getIns()).put("userinfo", json);
                ((IMineContact.IMineView) mView).getUserInfoSucc(response);

            }

            @Override
            protected void onNext(IUserInfo response) {
                super.onNext(response);
                ((IMineContact.IMineView) mView).getUserInfoFail(response);
            }

            @Override
            protected void onUnlogin(IUserInfo response) {
                super.onUnlogin(response);

                ((IMineContact.IMineView) mView).seleUnlogin(response);
            }

            @Override
            protected void onFailure(IUserInfo response) {
                super.onFailure(response);
                ((IMineContact.IMineView) mView).getUserInfoFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryUserCardFav() {
        AccessTokenRequest request = new AccessTokenRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        request.setAccess_token(access_token);
        mNetworkDateSource.queryUserCardFav(request, new SubscribeResult<UserCardFavResponse>() {
            @Override
            protected void onOk(UserCardFavResponse response) {
                Gson gson = new Gson();
                String json = gson.toJson(response);
//                L.e(Constant.TAG, "queryUserCardFav===" + json);
                List<UserCardFavResponse.DataBean> beanList = response.getData();
                if (mView != null) {
                    ((IMineContact.IMineView) mView).queryUserCardFavSucc(beanList);
                }
            }

            @Override
            protected void onNext(UserCardFavResponse response) {
                super.onNext(response);
//                PubUtils.popTipOrWarn(DaggerApplication.getIns(),response.getMessage());
            }

            @Override
            protected void onFailure(UserCardFavResponse response) {
                super.onFailure(response);
//                PubUtils.popTipOrWarn(DaggerApplication.getIns(),response.getMessage());

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
//                PubUtils.popTipOrWarn(DaggerApplication.getIns(),throwable.getMessage());

            }
        });
    }

    @Override
    public void getUserAdver() {
        QueryPageResourceReq pageResourceReq = new QueryPageResourceReq();
        pageResourceReq.setResource_area_id(33);
        pageResourceReq.setDevice_id("string");
        pageResourceReq.setSign("string");
        mNetworkDateSource.queryPageResource(pageResourceReq, new SubscribeResult<QueryPageResourceRes>() {
            @Override
            protected void onOk(QueryPageResourceRes response) {
                if (response != null) {
                    String json = new Gson().toJson(response);
                    L.e(Constant.TAG, "getUserAdverSucc---->" + json);
                    ((IMineContact.IMineView) mView).getUserAdverSucc(response);
                }
            }

            @Override
            protected void onFailure(QueryPageResourceRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void getWhxfInfo() {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        if (access_token != null) {
            accessTokenRequest.setAccess_token(access_token);
        }
        mNetworkDateSource.getUserDetails(accessTokenRequest, new SubscribeResult<HomeWhxfRes>() {
            @Override
            protected void onOk(HomeWhxfRes response) {
                List<HomeWhxfRes.CultureInforsBean> cultureInfors = response.getCultureInfors();
                if (cultureInfors != null) {

                    ((IMineContact.IMineView) mView).getWhxfInfoSucc(cultureInfors);
                }
            }

            @Override
            protected void onFailure(HomeWhxfRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });

    }

    @Override
    public void getAccessToken() {
        GetTokenReq getTokenReq = new GetTokenReq();
        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
        getTokenReq.setRefresh_token(refresh_token);
        getTokenReq.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        getTokenReq.setToken_type("1");
        mNetworkDateSource.getToken(getTokenReq, new SubscribeResult<GetTokenRes>() {
            @Override
            protected void onOk(GetTokenRes response) {
                String access_token = response.getAccess_token();
                ACache.get(DaggerApplication.getIns()).remove("access_token");
                ACache.get(DaggerApplication.getIns()).put("access_token", access_token);
                ((IMineContact.IMineView) mView).getAccessTokenSucc(response);
            }

            @Override
            protected void onNext(GetTokenRes response) {
                super.onNext(response);
            }

            @Override
            protected void onFailure(GetTokenRes response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void getOrderOpenid(final String type) {
        GetOrderOpenid getOrderOpenid = new GetOrderOpenid();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        getOrderOpenid.setAccess_token(access_token);
        getOrderOpenid.setTag("HUIMIN");
        String json = new Gson().toJson(getOrderOpenid);
        L.e(Constant.TAG, "getOrderOpenid----->" + json);
        mNetworkDateSource.getOrderOpenid(getOrderOpenid, new SubscribeResult<GetOrderOpenidRes>() {
            @Override
            protected void onOk(GetOrderOpenidRes response) {
                String toJson = new Gson().toJson(response);
                L.e(Constant.TAG, "-------------" + toJson);
                Constant.EXTENT = response.getExtend();
                ((IMineContact.IMineView) mView).getOrderOpenidSucc(response, type);
            }

            @Override
            protected void onFailure(GetOrderOpenidRes response) {
                super.onFailure(response);
                String toJson = new Gson().toJson(response);
                if (response.getCode().equals("0000")) {
                    String extend = response.getExtend();
                    ACache.get(DaggerApplication.getIns()).remove("mextend");
                    ACache.get(DaggerApplication.getIns()).put("mextend", response.getExtend());
                }
                L.e(Constant.TAG, "-------------" + toJson);
                ((IMineContact.IMineView) mView).getOrderOpenidSucc(response, type);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "getOrderOpenid" + throwable.getMessage());
            }
        });
    }

    @Override
    public void queryOrderCount() {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        String json = new Gson().toJson(accessTokenRequest);
        mNetworkDateSource.queryOrderCount(accessTokenRequest, new SubscribeResult<QueryOrderCountRes>() {
            @Override
            protected void onOk(QueryOrderCountRes response) {
                ((IMineContact.IMineView) mView).queryOrderCountSucc(response);
            }

            @Override
            protected void onFailure(QueryOrderCountRes response) {
                super.onFailure(response);
                ((IMineContact.IMineView) mView).queryOrderCountFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void selectUserAuth() {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        mNetworkDateSource.selectUserAuth(accessTokenRequest, new SubscribeResult<SeleciUserAuthRes>() {
            @Override
            protected void onOk(SeleciUserAuthRes response) {
                ((IMineContact.IMineView) mView).selectUserAuthSucc(response);
            }

            @Override
            protected void onUnlogin(SeleciUserAuthRes response) {
                super.onUnlogin(response);

//                ((IMineContact.IMineView) mView).seleUnlogin(response);
            }

            @Override
            protected void onFailure(SeleciUserAuthRes response) {
                super.onFailure(response);
//                Toast.makeText(DaggerApplication.getIns(), response.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void firstSearchUserLevel() {


        IBaseRequest baseRequest = new IBaseRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        baseRequest.setAccess_token(access_token);
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        baseRequest.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
        String key = "access_token=" + access_token + "&device_id=" + androidId + "&key=" + refresh_token;
        String stringMd5 = MD5Utils.getStringMd5(key).toUpperCase();
        baseRequest.setSign(stringMd5);
        mNetworkDateSource.firstSearchUserLevel(baseRequest, new SubscribeResult<FirstSearchUserLevelRes>() {
            @Override
            protected void onOk(FirstSearchUserLevelRes response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "认证等级---" + json);
                if (response.getData() == null || response.getData().getRecognitionLevel() == null) {
                    ((IRealNameContact.IRealNameView) mView).firstSearchUserLevelFail(response);
                    return;
                }
                AppHomeCardBean appHomeCardBean = new AppHomeCardBean();
                if (!StringUtils.isBlank(response.getData().getRecognitionLevel().getL3())) {
                    appHomeCardBean.setLevel("L3");
                    appHomeCardBean.setLevelDesc(response.getData().getRecognitionLevel().getL3());
                } else if (!StringUtils.isBlank(response.getData().getRecognitionLevel().getL2())) {
                    appHomeCardBean.setLevel("L2");
                    appHomeCardBean.setLevelDesc(response.getData().getRecognitionLevel().getL2());
                } else if (!StringUtils.isBlank(response.getData().getRecognitionLevel().getL1())) {
                    appHomeCardBean.setLevel("L1");
                    appHomeCardBean.setLevelDesc(response.getData().getRecognitionLevel().getL1());
                }
                if (response.getData().getRecognitionLevel() != null) {
                    String l2 = response.getData().getRecognitionLevel().getL2();
                    if (l2 != null) {
                        String[] split = l2.split("\\+");
                        String idCard = split[1];
                        appHomeCardBean.setIdCard(idCard);
                        Constant.USER_IDCARD = idCard;

                    }
                }
                Constant.USER_NAME = response.getData().getCustName();
                appHomeCardBean.setCustName(response.getData().getCustName());
                appHomeCardBean.setEcityCardNo(response.getData().getEcityCardNo());
                ((IMineContact.IMineView) mView).firstSearchUserLevelSucc(appHomeCardBean);
            }

            @Override
            protected void onFailure(FirstSearchUserLevelRes response) {
                super.onFailure(response);
                ((IMineContact.IMineView) mView).firstSearchUserLevelFail(response);
            }

            @Override
            protected void onNext(FirstSearchUserLevelRes response) {
                super.onNext(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
//                ((IRealNameContact.IRealNameView) mView).firstSearchUserLevelFail(response);
            }
        });

    }

    //获取用户当前总积分
    @Override
    public void queryUserCredit() {
        SignInReq signInReq = new SignInReq();
        signInReq.setAccess_token(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));

        mNetworkDateSource.getUserScore(signInReq, new SubscribeResult<SignInRes>() {
            @Override
            protected void onOk(SignInRes response) {
                ((IMineContact.IMineView) mView).queryUserCreditSucc(response);
            }

            @Override
            protected void onFailure(SignInRes response) {
                super.onFailure(response);
                ((IMineContact.IMineView) mView).queryUserCreditSucc(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void queryCouponCountSucc() {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        String json = new Gson().toJson(accessTokenRequest);
        mNetworkDateSource.queryCouponCount(accessTokenRequest, new SubscribeResult<CouponListBean>() {
            @Override
            protected void onOk(CouponListBean response) {
                ((IMineContact.IMineView) mView).queryCouponCountSucc(response);
            }

            @Override
            protected void onFailure(CouponListBean response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void userBehaviorBrowse(int id) {
        UserBehaviorBrowseReq userBehaviorBrowseReq = new UserBehaviorBrowseReq();
        userBehaviorBrowseReq.setModularId(id);
        userBehaviorBrowseReq.setAccessToken(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));

        mNetworkDateSource.userBehaviorBrowse(userBehaviorBrowseReq, new Action1<BaseBean>() {
            @Override
            public void call(BaseBean baseBean) {

                L.e(Constant.TAG, "ok----->" );
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    @Override
    public void queryNgFinance(String i) {
        QueryNgFinanceReq queryNgFinanceReq=new QueryNgFinanceReq();
        queryNgFinanceReq.setFlag(i);
        queryNgFinanceReq.setAccess_token(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));

        addSubscription(HttpDateSource.INSTANCE.createApi().queryNgFinance(queryNgFinanceReq), new ApiCallback<QueryNgFinanceRes>() {
            @Override
            public void onSuccess(@Nullable QueryNgFinanceRes response) {
                ((IMineContact.IMineView) mView).queryNgFinanceSucc(response);
            }
            @Override
            public void onFailure(@Nullable BaseBean model, @Nullable Throwable e) {
            }
        });
    }



}
